package com.yj.gateway.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 局部过滤器
 * 需自定义工厂（继承AbstractGatewayFilterFactory）后，加入该工厂
 * 然后在配置文件中的指定路由上配置
 */
@Slf4j
public class UserIdFilter implements GatewayFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("=====UserIdFilter begin=====");
        String userId = exchange.getRequest().getQueryParams().getFirst("userId");
        if(StringUtils.isEmpty(userId)){
            log.warn("=====UserIdFilter 非法访问=====");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        log.info("=====UserIdFilter end=====");
        return chain.filter(exchange);//继续下一个过滤器验证
    }

    @Override
    public int getOrder() {
        return 100;//加载过滤器的顺序，越小优先级越高，全局过滤器建议设为0
    }
}
